/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* build(vector<int>& preorder, vector<int>& postorder, int i0, int i1, int n)
    {
        if (n == 0) return nullptr;
        TreeNode* root = new TreeNode(preorder[i0]);
        if (n == 1) return root;

        int l = 1;
        for (; l < n; ++l)
            if (postorder[i1 + l - 1] == preorder[i0 + 1])
                break;

        root->left = build(preorder, postorder, i0 + 1, i1, l);
        root->right = build(preorder, postorder, i0 + l + 1, i1 + l, n - 1 - l);

        return root;
    }
    TreeNode* constructFromPrePost(vector<int>& preorder, vector<int>& postorder) {
        return build(preorder, postorder, 0, 0, postorder.size());
    }
};